import string
import random
import re
from email.policy import default

import django.http
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.decorators import method_decorator
from django.views import View
from django.http.response import JsonResponse
from django.core.mail import send_mail
from django.contrib.auth import get_user_model ,login,logout,get_user
from .models import *
from .forms import *
User = get_user_model()
# Create your views here.
def login_view(request):
    return render(request, 'login.html')
def register_view(request):
    return render(request, 'register.html')
def logout_view(request):
    logout(request)
    return JsonResponse({'code':200,'msg': '退出成功'})
class LoginAPI(View):
    def post(self,request):
        form = UserLoginForm(request.POST)
        if form.is_valid():
            account = form.cleaned_data['account']
            password = form.cleaned_data['password']
            user = User.objects.get(username=account)
            if user and user.check_password(password):
                if not form.cleaned_data['checked']:
                    request.session.set_expiry(0)
                login(request,user)
                return JsonResponse({'code':200,'msg':'登陆成功'})
        return JsonResponse({'code':400,'msg':'账户或密码错误'})

class RegisterAPI(View):
    def post(self, request):
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            account = form.cleaned_data['account']
            password = form.cleaned_data['password']
            email = form.cleaned_data['email']
            User.objects.create_user(username=account, password=password, email=email)
            return JsonResponse({'code':200,'msg': 'success'})
        else:
            return JsonResponse({'code':400,'msg':form.errors})
class EmailIdentify(View):
    def get(self, request):
        email = request.GET.get('email')
        if not re.match(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', email):
            return JsonResponse({'code': 400, 'msg': '请检查你的邮箱'})
        identify = "".join(random.sample(string.digits,4))
        """
        try:
            send_mail(
                "WCNM博客验证码,请必须乱传你的验证码",
                message=f"您的验证码是:{identify},祝您不得好死",
                recipient_list=[email],
                from_email=None
            )
        except Exception as e:
            return JsonResponse({'code': 400, 'msg': '你邮箱是不是有问题,发不出去'})
        """
        CaptchaIdentify.objects.update_or_create(email=email, defaults={'captcha': identify})
        return JsonResponse({'code': 200, 'msg': 'ok'})

class PostIconAPI(View):
    @method_decorator(login_required)
    def post(self, request):
        form = UserIconForm(request.POST,request.FILES,instance=request.user.profile)
        if form.is_valid():
            form.save()
            return JsonResponse({'code':200,'msg':'success'})
        print(form.errors)
        return JsonResponse({'code':400,'msg':form.errors})